package com.cdqidi.core.weixinmanager.config;

import com.cdqidi.constant.ConstantDto;
import com.cdqidi.core.weixinmanager.model.OrgWxConfig;
import com.cdqidi.core.weixinmanager.service.OrgWxConfigService;
import com.jfinal.springboot.weixin.config.WeiXinConfig;
import com.jfinal.springboot.weixin.config.WeiXinConfiguration;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.wxaapp.WxaConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author sjk
 * @create 2019-06-24 10:20
 * @since 1.0.0
 */
@Slf4j
@Component
public class WxSetConfig implements WeiXinConfig {


    private final OrgWxConfigService orgWxConfigService;

    @Autowired
    public WxSetConfig(OrgWxConfigService orgWxConfigService) {
        this.orgWxConfigService = orgWxConfigService;
    }


    @Override
    public void addWxConfigs(WeiXinConfiguration weiXinConfiguration) {
        log.info("开始加载微信配置文件--------------");
        List<OrgWxConfig> list = orgWxConfigService.getAll();
        if (null == list || list.isEmpty()) {
            return;
        }
        for (OrgWxConfig model : list) {
            log.info("name: " + model.getAppName() + ",appId: " + model.getAppId() + ",type: " + model.getWxAccountType() + ",appsecret: " + model.getAppSecret());
            //wxaccounttype4 小程序
            if (model.getWxAccountType().equals(ConstantDto.WX_ACCOUNT_TYPE_APP)) {
                WxaConfig wxaConfig = orgWxConfigService.convertToWxaConfig(model);
                weiXinConfiguration.getWxaConfigs().add(wxaConfig);
            } else {
                ApiConfig apiConfig = orgWxConfigService.convertToApiConfig(model);
                weiXinConfiguration.getWxConfigs().add(apiConfig);
            }
            model.freeData();
        }
        list.clear();
        log.info("完成微信配置文件加载------------");
        final List<WxaConfig> wxaConfigs = weiXinConfiguration.getWxaConfigs();
        for (WxaConfig wxaConfig : wxaConfigs) {
            log.info("小程序id: " + wxaConfig.getAppId());
        }
        final List<ApiConfig> wxConfigs = weiXinConfiguration.getWxConfigs();
        for (ApiConfig wxConfig : wxConfigs) {
            log.info("公众号id: " + wxConfig.getAppId());
        }
    }
}